package com.sanerzone.smscenter.modules.sms.task;

import com.sanerzone.jeebase.common.persistence.Page;
import com.sanerzone.jeebase.common.utils.DateUtils;
import com.sanerzone.jeebase.common.utils.JedisUtils;
import com.sanerzone.jeebase.common.utils.SpringContextHolder;
import com.sanerzone.smscenter.common.utils.AccountCacheUtils;
import com.sanerzone.smscenter.modules.account.service.BaseAccountService;
import com.sanerzone.smscenter.modules.sms.entity.SmsDayReport;
import com.sanerzone.smscenter.modules.sms.entity.SmsSend;
import com.sanerzone.smscenter.modules.sms.service.SmsDayReportService;
import com.sanerzone.smscenter.modules.sms.service.SmsSendService;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 每天订单数据转移到月订单表中
 */
@Lazy(false)
public class SmsSendOrderTransferTask {
	private static Logger logger = LoggerFactory.getLogger(SmsSendOrderTransferTask.class);
	private static final int BATCH_COMMIT_MAX_COUNT = 500;//批量提交默认值
	@Autowired
	private BaseAccountService baseAccountService;
	
	@Autowired
	private SmsDayReportService smsDayReportService;

	@Autowired
	private SmsSendService smsSendService;

	//每天 00:1:30执行日账务清算任务
	@Scheduled(cron = "30 1 0 * * ?")
//	@Scheduled(cron = "0/5 * * * * ?")
	@Transactional(readOnly = false)
	public void run(){
		SqlSession sqlSession = SpringContextHolder.getBean(SqlSessionFactory.class).openSession(ExecutorType.BATCH, false);
		try{
			int day = -4;
			
			String removeOrderTableName = "sms_send_"+DateUtils.getDayOfMonth(day); //订单每日表
			String transferTableName = "sms_send_history_"+DateUtils.getDayOfMonth(day);//订单历史月表
			SmsSend smsSendRemoveVO = new SmsSend();
			smsSendRemoveVO.setTableName(removeOrderTableName);
			Page page= new Page(1,2);
			smsSendRemoveVO.setPage(page);
			SmsSend smsSendTransferVO = new SmsSend();
			smsSendTransferVO.setTableName(removeOrderTableName);

			List<SmsSend> list =  smsSendService.findList(smsSendRemoveVO);
			while (list != null && list.size() > 0) {

				int i = 0;
				for (SmsSend smsSend :list) {
					i++;
//					sqlSession.insert("com.sanerzone.smscenter.modules.sms.dao.SmsSendDao.insert", smsSend);//批量提交
//					sqlSession.delete("com.sanerzone.smscenter.modules.sms.dao.SmsSendDao.detele", smsSend.getId());//批量提交
					if(i % BATCH_COMMIT_MAX_COUNT == 0){
						sqlSession.commit();
					}
				}
			}
		}catch(Exception e){
			logger.error("定时任务,执行日账务清算任务失败",e);
		}finally {
			if (sqlSession!=null){
				sqlSession.close();
			}
		}
	}
	
}
